package com.zero.common.security.service;

import com.zero.common.core.constant.CacheConstants;
import com.zero.common.system.domain.entity.SysUser;
import com.zero.common.core.redis.RedisTemplateHelper;
import com.zero.common.core.exception.user.UserPasswordNotMatchException;
import com.zero.common.core.exception.user.UserPasswordRetryLimitExceedException;
import com.zero.common.security.context.LoginAuthenticationContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 登录密码方法
 *
 * @author ruoyi
 */
@Component
public class SysPasswordService {
    @Autowired
    private RedisTemplateHelper redisTemplateHelper;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    /**
     * 校验密码
     * @param user 用户信息
     */
    public void validate(SysUser user) {
        // 上下文(账号密码)
        Authentication usernamePasswordAuthenticationToken = LoginAuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();
        // 重试次数
        Integer retryCount = redisTemplateHelper.getCacheObject(getCacheKey(username));
        if (retryCount == null) {
            // 第一次输入密码
            retryCount = 0;
        } else if (retryCount >= maxRetryCount) {
            // 重试耗尽
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }
        if (!new BCryptPasswordEncoder().matches(password, user.getPassword())) {
            // 密码错误
            retryCount = retryCount + 1;
            redisTemplateHelper.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        } else {
            // 密码正确
            clearLoginRecordCache(username);
        }
    }

    /**
     * 删除用户剩余密码重试次数
     * @param loginName 账号
     */
    public void clearLoginRecordCache(String loginName) {
        if (redisTemplateHelper.hasKey(getCacheKey(loginName))) {
            redisTemplateHelper.deleteObject(getCacheKey(loginName));
        }
    }
}
